import 'dart:convert';

import 'package:imperius_insights/entity/bugstats.dart';
import 'package:imperius_insights/portal/channels/factory.dart';
import 'package:imperius_insights/portal/channels/web.dart';
import 'package:imperius_insights/treaty/endpoint.dart';

class Service {
  Future<IssuesClassification> queryIssues(String pmo) async {
    final channel = Channels.shared<WebChannel>(ChannelType.Web);
    final params = {
      'moduleSelect': 'mudidi_rexian_wenti',
      'type': 'todolist',
      'dimension': 'Bug状态及优先级数量统计',
      'pmoNumber': pmo
    };
    final response =
        await channel.invoke(target: queryIssuesClassification, params: params);
    final json = jsonDecode(response);
    final table = json['data']['echarts1']['rows'];
    return IssuesClassification(
      p1Count: _classifyTotalCount(table, 'P1'),
      p2Count: _classifyTotalCount(table, 'P2'),
      p3Count: _classifyTotalCount(table, 'P3'),
      p4Count: _classifyTotalCount(table, 'P4'),
      suggestionCount: _classifyTotalCount(table, '优化建议'),
      uiIssuesCount: _classifyTotalCount(table, 'UI展示及文案'),
      unresolvedCount: _statefulTotalCount(table, 1),
      resolvingCount: _statefulTotalCount(table, 2),
      resolvedCount: _statefulTotalCount(table, 3),
      verifyingCount: _statefulTotalCount(table, 5),
      reopenedCount: _statefulTotalCount(table, 6),
    );
  }

  Future<BugOutlineStats> queryOutline(String pmo) async {
    final channel = Channels.shared<WebChannel>(ChannelType.Web);
    final params = {'projectId': pmo};
    final response =
        await channel.invoke(target: queryCaseCount, params: params);
    final json = jsonDecode(response);
    final nodeData = json['data'];
    return BugOutlineStats(
      totalCount: nodeData['totalCount'],
      hasExecuted: nodeData['hasExecuted'],
      unExecuted: nodeData['unExecuted'],
      caseTotal: nodeData['caseTotal'],
      rdExecutiveCount: nodeData['rdExecutiveCount'],
      rdExecutiveRate: nodeData['rdExecutiveRate'],
      bugTotal: nodeData['bugTotal'],
      bugRate: nodeData['bugRate'],
      executedNotPass: nodeData['executedNotPass'],
      notRdExecutiveCount: nodeData['notRdExecutiveCount'],
      notRdExecutiveRate: nodeData['notRdExecutiveRate'],
    );
  }

  Future<List<BugItem>> queryBugs(String pmo) {

  }

  int _statefulTotalCount(List<dynamic> table, int statusInPosition) {
    return table.map((e) => int.parse(e[statusInPosition])).reduce((value, element) => value + element);
  }

  int _classifyTotalCount(List<dynamic> table, String classType) {
    final index = table.indexWhere((strList) => strList[0] == classType);
    if (index < 0) {
      return 0;
    }
    return int.parse(table[index][8]);
  }
}
